<?php
require_once dirname(__FILE__) . '/GoogleClientApi/Google_Client.php';
require_once dirname(__FILE__) . '/GoogleClientApi/contrib/Google_YouTubeService.php';

//require_once 'Zend/Loader.php';
//$frontController = Zend_Controller_Front::getInstance();
//$appConfig = $frontController->getParam('bootstrap')->getOptions();
$client = new Google_Client();
$client->setDeveloperKey("AIzaSyAXsMaLR1ELiBTit2XqmrYfMS3pb7XLiOo"); // API key
    $youtube = new Google_YoutubeService($client);
try {

    $ytSearchStr = "再生リスト";
    $maxResults = "10";
    $type = "playlist";
    $get_order= 'rating';
   // $videoCategoryId =10;

    $ytRes1st = $youtube->search->listSearch('id,snippet', array(
        'q' => $ytSearchStr,
        'maxResults' => $maxResults,
        'order' => '$get_order',
        'type' => $video,
      //  'publishedAfter' => $publishedAfter,
      //  'publishedBefore' => $publishedBefore,
    //    'videoCategoryId' => 10,
        'pageToken' => $get_pageToken,
        'order' => $get_order,
    ));
// APIレスポンス
    if ($ytRes1st) {
// ページ情報の保存
        $ytRes1st_kind = $ytRes1st['kind'];
        $ytRes1st_etag = $ytRes1st['etag'];
        $ytRes1st_totalResults = $ytRes1st['pageInfo']['totalResults'];
        $ytRes1st_resultsPerPage = $ytRes1st['pageInfo']['resultsPerPage'];
        $ytRes1st_nextPageToken = $ytRes1st['nextPageToken'];
        $ytRes1st_prevPageToken = $ytRes1st['prevPageToken'];
// 変数準備
        $movies = '';
        $channelIds = '';
        $videoIds = '';
        $results = array();
// 検索結果の保存
        foreach ($ytRes1st['items'] as $item) {
            $movieTitle = $item['snippet']['title'];
            $channelId = $item['snippet']['channelId'];
            $channelTitle = $item['snippet']['channelTitle'];
            $publishedAt = $item['snippet']['publishedAt'];
            $videoId = $item['id']['videoId'];
            $videoIds .= $item['id']['videoId'] . ",";          // 動画再生回数、like・dislikeの取得用
            $moviePath = '/v';
// 検索結果は一旦配列に保存する（ループが多くなるので極力APIリクエストを減らす）
            $results[] = array('movieTitle' => $movieTitle,
                'channelId' => $channelId,
                'publishedAt' => $publishedAt,
                'videoId' => $videoId,
            );
        }
    }

// 動画再生回数、like・dislikeの取得
// APIリクエスト用のビデオID（複数）最後のカンマを削除
    $videoIds = rtrim($videoIds, ",");
// APIリクエスト
    $ytRes2nd = $youtube->videos->listVideos($videoIds, 'snippet,statistics,contentDetails', array());
    $i = 0;
    
  
// APIレスポンス
    if ($ytRes2nd) {
        foreach ($ytRes2nd['items'] as $item) {
            $ytRes2nd_channelId = $item['snippet']['channelId'];                    // チャンネルID
            $thumbnail = $item['snippet']['thumbnails']['default']['url']; // サムネイル
              var_export($item['snippet']['thumbnails']['default']);
            $duration = $item['contentDetails']['duration'];              // 動画時間
            $viewCount = $item['statistics']['viewCount'];                 // 再生数
            $likeCount = $item['statistics']['likeCount'];                 // 高評価数
            $dislikeCount = $item['statistics']['dislikeCount'];              // 低評価数
// 配列の最後に追加する
            $results[$i] += array("thumbnail" => $thumbnail,
                "duration" => $duration,
                "viewCount" => $viewCount,
                "likeCount" => $likeCount,
                "dislikeCount" => $dislikeCount,
            );
            $i = $i + 1;
        }
    }

    $htmlBody = "<ol>\n";

    foreach ($results as $key => $value) {
        $htmlBody .= <<<END
<li>
<img src="{$value["thumbnail"]}" /> imgsrc="{$value["thumbnail"]}"<br />
{$value["movieTitle"]}<br />
再生回数：{$value["viewCount"]}<br />
投稿者：{$value["channelId"]}<br />
再生時間：{$value["duration"]}<br />
投稿日：{$value["publishedAt"]}
</li>\n
END;
    }

    $htmlBody .= "</ol>\n";
} catch (Google_ServiceException $e) {
    $htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
    $htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage()));
}
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>YouTube Search</title>
    </head>
    <body>
<?php echo $htmlBody; ?>
    </body>
</html>